package me.leiusual.sharing.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_address_edit.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.Address
import me.leiusual.sharing.api.model.AddressRegion
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.mine.adapter.MineAddressEditAdapter
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-28
 * description:
 */
class MineAddressEditFragment : DaggerFragment(), AdapterView.OnItemClickListener, View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineAddressEditViewModel by viewModels { factory }

  private val args: MineAddressEditFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_address_edit, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_send_sms.setOnClickListener(this)

    // 自动补全
    val adapter = MineAddressEditAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line)
    adapter.addressRepository = viewModel.addressRepository
    edit_text_province.setAdapter(adapter)
    edit_text_province.onItemClickListener = this

    button_update.setOnClickListener(this)

    tryFillData()

    observeData()
  }

  override fun onDestroyView() {
    super.onDestroyView()

    val adapter = edit_text_province.adapter as MineAddressEditAdapter
    adapter.cancel()
  }

  override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
    val addressRegion = parent?.getItemAtPosition(position) as? AddressRegion
    Timber.v("onItemClick addressRegion = %s", addressRegion)
    if (addressRegion != null) {
      viewModel.addressRegion(addressRegion)
    }
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_send_sms -> {
        doVerifyCode()
      }
      R.id.button_update -> {
        doAddressUpdate()
      }
    }
  }

  private fun tryFillData() {
    val address = args.address
    if (address == null) {
      text_view_title.text = "编辑收货地址"
      button_update.text = "保存"

    } else {
      text_view_title.text = "更新收货地址"
      button_update.text = "更新"

      viewModel.addressRegion(AddressRegion(address.countyId, address.provCityCounty))

      edit_text_name.setText(address.linkMan)
      edit_text_phone.setText(address.contactPhone)
      edit_text_province.setText(address.provCityCounty)
      edit_text_address.setText(address.detailAddress)
      switch_default.isChecked = address.defaulted
      switch_default.isEnabled = !address.defaulted
    }
  }

  private fun observeData() {
    viewModel.addressSms.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("addressSms = %s", it)
      when (it) {
        is Data.Loading -> {
          text_view_send_sms.isEnabled = false
        }
        is Data.Error -> {
          text_view_send_sms.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          text_view_send_sms.startTimber()
          toast("短信发送成功！")
        }
      }
    })

    viewModel.addressUpdate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("addressUpdate = %s", it)
      when (it) {
        is Data.Loading -> {
          button_update.isEnabled = false
        }
        is Data.Error -> {
          button_update.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_update.isEnabled = true
          findNavController().popBackStack()
        }
      }
    })
  }

  private fun doVerifyCode() {
    val phone = edit_text_phone.text.toString()

    viewModel.addressSms(phone)
  }

  private fun doAddressUpdate() {
    val name = edit_text_name.text.toString()
    val phone = edit_text_phone.text.toString()
    val verifyCode = edit_text_verify_code.text.toString()
    val address = edit_text_address.text.toString()
    val defaulted = switch_default.isChecked

    val addressRegion = viewModel.addressRegion.value
    if (addressRegion == null) {
      toast("请输入正确的省市区县")
      return
    }

    val newAddress = Address(
        args.address?.id ?: 0,
        name,
        phone,
        if (verifyCode.isNotEmpty()) verifyCode else args.address?.verifyCode,
        addressRegion.id,
        addressRegion.value,
        address,
        defaulted,
        args.address?.encryptedCode
    )
    viewModel.addressUpdate(newAddress)
  }
}